home *** CD-ROM | disk | FTP | other *** search
- Path: inforamp.net!usenet
- From: rmorin@inforamp.net (Randy Charles Morin)
- Newsgroups: comp.lang.c++
- Subject: Re: Saving the contents of an object to a file
- Date: Fri, 19 Apr 1996 03:23:10 GMT
- Organization: InfoRamp Inc., Toronto, Ontario (416) 363-9100
- Message-ID: <4l6mek$ah3@sam.inforamp.net>
- References: <31739D83.5F61@mars.superlink.net>
- NNTP-Posting-Host: ts47-12.tor.istar.ca
- X-Newsreader: Forte Free Agent 1.0.82
-
- Michael Rizzo <rizzom@mars.superlink.net> wrote:
- > I am having a problem saving the contents of an object to a
- >file. For instance, I have the following code:
- >
- >int main()
- >{
- > A x(10,"JOE"), y;
- > ofstream outf("savefile",ios::binary);
- > outf.write((char*) &x, sizeof x);
- > outf.write((char*) &y, sizeof y);
- > outf.close();
- > return 0;
- >}
-
- try...
- ofstream outf("savefile", ios::binary+ios::out);
-
- but this won't work either, because you'd be saving only an int and a
- pointer. The string won't get saved.
-
- try the following...
-
- class A
- {
- private:
- int id;
- char *name;
- public:
- A(int, char*);
- A();
- ~A();
- char * GetName() {return name;}
- int GetId() {return id;}
- friend ipstream & operator >> ( ipstream &is, MWDeltaFile &p );
- friend opstream & operator << ( opstream &os, const MWDeltaFile &p );
- };
-
- ofstream & operator << ( opstream &os, const A &r )
- {
- r << id << name;
- };
-
- A::A(int i, char *n)
- {
- int temp;
- id = i;
- temp = strlen(n);
- name = new char[temp+1];
- strcpy(name,n);
- }
-
- A::A()
- {
- id = 0;
- name = new char[5];
- strcpy(name, "none");
- }
-
- int main()
- {
- A x(10,"JOE"), y;
- ofstream outf("savefile",ios::binary+ios::binary+ios::out);
- outf << x << y;
- return 0;
- }
-
- Hope I've helped
-
-
- Agrivar
-
- aka Randy Charles Morin,
- MiddleWorld SoftWare,
- Satisfying Your Bit and Bytes,
- Canada 1-800-363-3780
- Other 1-905-279-2087
- eMail rmorin@inforamp.net
-
-